package xyz.bernkastel.goods_in_great_demand.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import xyz.bernkastel.goods_in_great_demand.common.R;
import xyz.bernkastel.goods_in_great_demand.common.SMSUtils;
import xyz.bernkastel.goods_in_great_demand.entity.Employee;
import xyz.bernkastel.goods_in_great_demand.entity.User;
import xyz.bernkastel.goods_in_great_demand.service.UserService;
import xyz.bernkastel.goods_in_great_demand.common.ValidateCodeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        if (!StringUtils.isEmpty(phone)) {
            //获取验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);
            //调用api发送短信


            //没有权力发短信......
            SMSUtils.sendMessage("俏货", "", phone, code);

            //将生成的验证码保存到session中
            session.setAttribute(phone, code);
            return R.success("验证码发送成功！");

        }
        return R.error("验证码发送失败!");

    }

    /**
     * 登录
     *
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info(map.toString());
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        String codeInSession = session.getAttribute(phone).toString();

        if (codeInSession != null && codeInSession.equals(code)) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User currentUser = userService.getOne(queryWrapper);
            if (currentUser == null) {
                currentUser = new User();
                currentUser.setStatus(1);
                currentUser.setPhone(phone);
                userService.save(currentUser);
            }
            session.setAttribute("user", currentUser.getId());
            return R.success(currentUser);


        }


        return R.error("登陆失败!");

    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出成功");
    }

    @PutMapping
    public R<String> edit(HttpServletRequest request, @RequestBody User user) {
        log.info(user.toString());

        //JS对Long数据处理会丢失精度，需要转换成String
        Long userId = (Long) request.getSession().getAttribute("user");
//
//        user.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(employeeId);
//        employeeService.updateById(employee);
        user.setId(userId);
        userService.updateById(user);
        return R.success("更新用户信息成功");
    }

    /**
     * 根据id来查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<User> getById(@PathVariable Long id) {
        log.info("根据id查询用户信息");
        User user = userService.getById(id);
        if (user != null) {
            return R.success(user);
        }
        return R.error("未查询到对应用户信息");
    }
}
